package tweet.response;

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.Exception;
import javafx.scene.Group;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.lang.FX;
import javafx.scene.CustomNode;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.Node;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.data.Pair;
import javafx.io.http.HttpHeader;
import javafx.io.http.HttpRequest;
import javafx.io.http.URLConverter;
import javax.swing.JOptionPane;
import javafx.scene.control.TextBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.animation.transition.FadeTransition;
import desktop.agent.*;
import tweet.response.*;
public class TweetResponse extends CustomNode {

 	public def myWidth = 240;
 	public def myHeight = 360;
	
	var myStage : Stage;
	var sessionUtil : ServiceUtil;
	var tweeterUser = "{FX.getArgument('tweeterUser')}";
	var tweeterPass= "{FX.getArgument('tweeterPass')}";
	
	public var text : String;
	
	public var titleImage = Image { url: "{__DIR__}images/twitter2.png"};
	public var replyImage = Image {url: "{__DIR__}images/tweet11.png"  };
	public var closeImage = Image {url: "{__DIR__}images/close.png"
 	        width: 14
 	        height: 14
 	    };	 
 
    public var backgroundImageURL : String = "{__DIR__}images/bg.png";
     
    
    function getBackgroundImage(url : String) : Image {
        Image {
            url: url
            backgroundLoading: true
        }
    }
    public var textColor : String = "333333";
    public var linkColor : String = "0093FF";
    public var backgroundColor : String = "F8F8F8";

    var bgImageURL = bind backgroundImageURL;
       
 	var bgRect = Rectangle {
		x: 0
		y: 0
		width: myWidth
		height: myHeight
		fill: Color.ALICEBLUE
		arcWidth: 5
     	arcHeight: 5
	 };
	          
     var bgImage = ImageView {
         translateX: 5
         translateY: 5
         image: bind getBackgroundImage(bgImageURL)
         fitWidth: (myWidth - 10)
         fitHeight: (myHeight - 10)
         opacity: 1.0
     };
      
     var borderRect = Rectangle {
	      x: 2
	      y: 2
	      width: myWidth - 4
	      height: myHeight - 4
	      strokeWidth: 1.5
	      stroke: bind Color.web("#{linkColor}")
	      fill: Color.TRANSPARENT
	      arcWidth: 5
	      arcHeight: 5
	 }; 
      
     var titleImage2 = ImageView {
     	translateX: 5
  		translateY: 5
  		image: bind titleImage
  		opacity: 1.0
     };    
         
     
     var tweetMessage = Rectangle {
            x: 10
            y: 50
            width: myWidth - 20
            height: 170  //70
            strokeWidth: 1.5
            stroke: bind Color.web("#{linkColor}")
            fill: Color.TRANSPARENT
            arcWidth: 5
            arcHeight: 5
            opacity: 0.9
        };
        
     
        
     var message = Text {
            x: 12
            y: 65
            font: Font { name: "Bitstream Vera Sans Bold" size: 11 }
            wrappingWidth: 180
            fill: Color.web("#{textColor}")
            content: bind text
        };
 
	var tweetTextBox : TextBox = TextBox {
    	translateX: 10
        translateY: 230  //140
        width: (myWidth -20)
        height: (50)
        opacity: 0.9
        font: Font { name: "Bitstream Vera Sans Bold" size: 10 }
        action: function() {
            tweetTextBox.commit();
            addStatus("{tweetTextBox.text}");
            tweetTextBox.text = "";
            
        }
    }

    

	var replyButton = ImageButton {
    	normalImage: replyImage
        translateX: 70
        translateY: 290 //220
        visible:true 
        opacity: 1.0
        onMousePressed: function(e) {
            tweetTextBox.commit();
			addStatus("{tweetTextBox.rawText}");
            tweetTextBox.text = "";
        }
    };

 
	protected var fadeTransition = FadeTransition {
		duration: 250ms
    	node: this
    	fromValue: 0.0
    	toValue: 1.0
    	action: function() {
        	visible = true;
    	}
	};    

	var closeButton = ImageButton {
        normalImage: closeImage
        translateX: myWidth - 19
        translateY: 5
        visible:true  
        onMousePressed: function(e) {
            sessionUtil.drop();
   			fadeTransition.stop();
            fadeTransition.fromValue = 1.0;
            fadeTransition.toValue = 0.0;
            fadeTransition.playFromStart();
            visible = false;
        }
    };

 
    
    override function create() : Node {
         Group { 
        	content: bind [ bgRect, bgImage,titleImage2, closeButton, borderRect, tweetMessage, message,  tweetTextBox, replyButton ]
         };
        
        
    }
	
	
		
	public function start(myUser:String, message:String, stage:Stage, sessionService:ServiceUtil) : Void {
        text = message;
        sessionUtil = sessionService;
    }
    
    public function setText(message:String) : Void {
        text = message;
    }
    
    public function setVisible() : Void {
   		fadeTransition.stop();
        fadeTransition.fromValue = 0.0;
        fadeTransition.toValue = 1.0;
        fadeTransition.playFromStart();
		visible = true;
    }
    
    public function setInvisible() : Void {
        fadeTransition.stop();
		fadeTransition.fromValue = 1.0;
        fadeTransition.toValue = 0.0;
        fadeTransition.playFromStart();
        visible = false;
    }
    
    public function trimString(string:String, length:Integer) : String {
    
        if(string == null) return "";
    
        if(string.length() > length) {
            return "{string.substring(0, length).trim()}...";
        } else {
            return string;
        }
    }
    
     function addStatus(message : String) : Void {
    
            if(not ((message != null) and (message.trim().length() > 0))) {
                return;
            }
            
            var httpHeader = HttpHeader.basicAuth(tweeterUser, tweeterPass);
            var httpRequest = HttpRequest {
    
                location: "http://twitter.com/statuses/update.xml"
                headers: [ httpHeader ]
                method: HttpRequest.POST
    
                onInput: function(is: InputStream) {
                    is.close();
                }
    
                onOutput: function(os: OutputStream) {
                    var urlConverter = URLConverter{};
                    var pair = Pair {
                        name: "status"
                        value: trimString("{message}", 140)
                    };
                    var encodedMessage = urlConverter.encodeParameters([pair]);
                    os.write(encodedMessage.getBytes());
                    os.close();
                }
    
                onException: function(ex: Exception) {
                    //onException("{ex.getMessage()}");
                }
    
                onDone: function() {
                    //updateStatusList();
                }
            };
            httpRequest.start();
        }
}
